/*
 * GamePanel.java
 *
 */
package videogame;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.Collections;
import vision.BasicOps;
import vision.objects.ImageObject;
import vision.MotionDetector;
import vision.objects.ObjectAnalysis;
import vision.input.VideoInput;
import vision.input.VideoInputs;

/**
 *
 * @author  Kotuc
 */
public class GamePanel extends javax.swing.JPanel implements Runnable {

    /** Creates new form GamePanel */
    public GamePanel() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        scoreLabel = new javax.swing.JLabel();
        healthLabel = new javax.swing.JLabel();
        timeProgress = new javax.swing.JProgressBar();
        elapsedLabel = new javax.swing.JLabel();
        timeleftLabel = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        fpsLabel = new javax.swing.JLabel();

        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        jButton1.setText("start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        scoreLabel.setFont(new java.awt.Font("Tahoma", 1, 48));
        scoreLabel.setForeground(new java.awt.Color(102, 255, 255));
        scoreLabel.setText("jLabel1");

        healthLabel.setText("jLabel1");

        elapsedLabel.setFont(new java.awt.Font("Tahoma", 1, 48));
        elapsedLabel.setForeground(new java.awt.Color(255, 51, 0));
        elapsedLabel.setText("jLabel1");

        timeleftLabel.setFont(new java.awt.Font("Tahoma", 1, 48));
        timeleftLabel.setForeground(new java.awt.Color(255, 51, 0));
        timeleftLabel.setText("jLabel1");

        jButton2.setText("snap background");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("select device");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        fpsLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        fpsLabel.setForeground(new java.awt.Color(204, 51, 0));
        fpsLabel.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(timeProgress, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(scoreLabel))
                    .addComponent(healthLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(elapsedLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE)
                        .addComponent(timeleftLabel))
                    .addComponent(fpsLabel))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scoreLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2)
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fpsLabel)
                .addGap(98, 98, 98)
                .addComponent(healthLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(elapsedLabel)
                    .addComponent(timeleftLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(timeProgress, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        new Thread(this).start();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
        board.attack(evt.getX(), evt.getY());
    }//GEN-LAST:event_formMouseMoved

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        iprocess.setStaticBackground(BasicOps.horizontalFlip(videoIn.snap()));
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    }//GEN-LAST:event_jButton3ActionPerformed
    private ImageProcess iprocess = new ImageProcess();
    private Board board = new Board();
    private VideoInput videoIn = VideoInputs.getVideo();
    private ObjectAnalysis analysis = new ObjectAnalysis();
    private MotionDetector mdetect = new MotionDetector();
    private BufferedImage bground;
    private Collection<ImageObject> objects = Collections.emptySet();
    private Image bgimage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/monsters/bg1.png"));

    public void run() {



        long curTime = System.currentTimeMillis();
        board.startTime = curTime;
        board.endTime = board.startTime + 10000;

        try {

            int frames = 0;

//        while ((curTime = System.currentTimeMillis()) < board.endTime) {
            while (true) {

                frames++;

                BufferedImage snap = videoIn.snap();
                // mirror effect
                snap = BasicOps.horizontalFlip(snap);

                board.width = snap.getWidth();
                board.height = snap.getHeight();

                snap = iprocess.process(snap);
//                snap = mdetect.getMotion(snap);
//                snap = analysis.prepairImage(snap);

                objects = analysis.findObjects(iprocess.zones);
//                objects = analysis.findObjects(snap);

                bground = snap;

                for (ImageObject imageObject : objects) {
                    int col = imageObject.getColor();
                    if (col == ImageProcess.ATTACK_RED) {
                        board.attack(imageObject);
                    } else {
                        System.out.println("color: " + Integer.toHexString(imageObject.getColor()));
                    }
                }


                board.moves();

                fpsLabel.setText("" + 1000 * frames / board.getRunTime() + " fps");
                scoreLabel.setText("Your score: " + board.score);
                elapsedLabel.setText("Elapsed time: " + board.getRunTime());
                timeleftLabel.setText("Time left: " + (board.endTime - curTime));

                timeProgress.setValue((int) (100 * (board.getRunTime()) / (board.endTime - board.startTime)));


                repaint();
                Thread.sleep(20);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.GREEN);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.drawImage(bgimage, 0, 0, getWidth(), getHeight(), null);
        if (bground != null) {
            Graphics bg = bground.getGraphics();

            for (ImageObject obj : objects) {
                bg.setColor(new Color(0xFFFF0000 | obj.getColor()));
                bg.drawRect(obj.getMinX(), obj.getMinY(), obj.getWidth(), obj.getHeight());
            }

            board.paintMonsters(bg);
        }
        g.drawImage(bground, 0, 0, getWidth(), getHeight(), null);


        paintComponents(g);

//        super.paint(g);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel elapsedLabel;
    private javax.swing.JLabel fpsLabel;
    private javax.swing.JLabel healthLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel scoreLabel;
    private javax.swing.JProgressBar timeProgress;
    private javax.swing.JLabel timeleftLabel;
    // End of variables declaration//GEN-END:variables
}
